#include "microgridmanager.h"
#include "optimizationalgorithm.h" // 假设有一个优化算法类
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDateTime>
#include <QThread>

MicrogridManager::MicrogridManager(QObject* parent)
    : QObject(parent)
    , optimizationAlgorithm(nullptr)
    , simulationRunning(false)
    , totalPower(0.0)
    , totalCost(0.0)

{
    // 初始化优化算法（可以使用默认算法）
    optimizationAlgorithm = new OptimizationAlgorithm(this);
}

MicrogridManager::~MicrogridManager()
{
    // 清理所有组件
    qDeleteAll(componentsMap);
    componentsMap.clear();

    // 清理优化算法
    delete optimizationAlgorithm;
}

void MicrogridManager::addComponent(Component* component)
{
    if (!component || !validateComponent(component)) {
        emit errorOccurred("无效的组件");
        return;
    }

    QString name = component->getName();
    if (componentsMap.contains(name)) {
        emit errorOccurred(QString("已存在同名组件: %1").arg(name));
        return;
    }

    componentsMap.insert(name, component);
    emit componentAdded(name, component);
    emit statusUpdated(QString("添加组件: %1").arg(name));
}

bool MicrogridManager::removeComponent(const QString& name)
{
    if (!componentsMap.contains(name)) {
        emit errorOccurred(QString("组件不存在: %1").arg(name));
        return false;
    }

    Component* component = componentsMap.take(name);
    delete component;
    emit componentRemoved(name);
    emit statusUpdated(QString("移除组件: %1").arg(name));
    return true;
}

Component* MicrogridManager::getComponent(const QString& name) const
{
    return componentsMap.value(name, nullptr);
}

QVector<Component*> MicrogridManager::getAllComponents() const
{
    return componentsMap.values().toVector();
}

int MicrogridManager::getComponentCount() const
{
    return componentsMap.size();
}

bool MicrogridManager::loadDataFromCSV(const QString& filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        emit errorOccurred(QString("无法打开文件: %1").arg(filename));
        return false;
    }

    QTextStream in(&file);
    // 跳过标题行
    QString header = in.readLine();

    // 读取数据（这里需要根据实际的CSV格式进行解析）
    // 简化实现：假设CSV包含时间、价格、负荷等数据

    electricityPrices.clear();
    loadProfile.clear();

    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(",");

        if (fields.size() >= 3) {
            // 假设格式：时间,价格,负荷
            electricityPrices.append(fields[1].toDouble());
            loadProfile.append(fields[2].toDouble());
        }
    }

    file.close();
    emit statusUpdated(QString("从CSV加载数据: %1").arg(filename));
    return true;
}

bool MicrogridManager::saveResultsToCSV(const QString& filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        emit errorOccurred(QString("无法创建文件: %1").arg(filename));
        return false;
    }

    QTextStream out(&file);
    out << "时间,优化结果,实际功率,成本\n";

    for (int i = 0; i < optimizationResult.size(); ++i) {
        out << i << ","
            << optimizationResult[i] << ","
            << totalPower << ","
            << totalCost << "\n";
    }

    file.close();
    emit statusUpdated(QString("保存结果到CSV: %1").arg(filename));
    return true;
}

// 新增：电价数据导入实现
void MicrogridManager::importPriceData(const QVector<double>& prices)
{
    if (prices.size() != SIMULATION_TIME_STEPS) {
        emit errorOccurred("电价曲线长度必须为96（24h×15min）");
        return;
    }
    electricityPrices = prices;
    emit statusUpdated("电价数据导入完成");
}

// 新增：负荷曲线导入实现
void MicrogridManager::importLoadProfile(const QVector<double>& profile)
{
    if (profile.size() != SIMULATION_TIME_STEPS) {
        emit errorOccurred("负荷曲线长度必须为96（24h×15min）");
        return;
    }
    loadProfile = profile;
    emit statusUpdated("负荷曲线导入完成");
}

void MicrogridManager::optimizeSchedule()
{
    if (componentsMap.isEmpty()) {
        emit errorOccurred("没有可优化的组件");
        return;
    }

    emit optimizationStarted();

    // 调用优化算法进行调度优化
    if (optimizationAlgorithm) {
        // 模拟优化过程（实际实现需要调用优化算法）
        optimizationResult = optimizationAlgorithm->optimize(
            componentsMap.values().toVector(),
            electricityPrices,
            loadProfile
            );

        // 发送优化进度信号（简化实现）
        for (int i = 0; i <= 100; i += 10) {
            emit optimizationProgress(i);
            // 模拟优化计算时间
            QThread::msleep(100);
        }

        emit optimizationCompleted(optimizationResult);
        emit statusUpdated("优化完成");
    } else {
        emit errorOccurred("未设置优化算法");
    }
}
// 新增：获取当前时间步
int MicrogridManager::getCurrentTimeStep() const
{
    return currentTimeStep;
}
void MicrogridManager::startSimulation()
{
    if (simulationRunning) {
        emit errorOccurred("仿真已在运行中");
        return;
    }

    simulationRunning = true;
    emit simulationStarted();
    emit statusUpdated("仿真开始");

    // 初始化组件
    initializeComponents();

    // 计算初始总功率和成本
    calculateTotalPower();
    calculateTotalCost();
}


void MicrogridManager::pauseSimulation()
{
    if (!simulationRunning) {
        emit errorOccurred("仿真未运行");
        return;
    }

    simulationRunning = false;
    emit simulationPaused();
    emit statusUpdated("仿真暂停");
}

void MicrogridManager::stopSimulation()
{
    simulationRunning = false;
    emit simulationStopped();
    emit statusUpdated("仿真停止");
}

void MicrogridManager::resetSimulation()
{
    stopSimulation();

    // 重置所有组件
    for (Component* component : componentsMap) {
        component->setPower(0);
    }

    optimizationResult.clear();
    totalPower = 0.0;
    totalCost = 0.0;

    emit simulationReset();
    emit statusUpdated("仿真重置");
}

double MicrogridManager::getTotalPower() const
{
    return totalPower;
}

double MicrogridManager::getTotalCost() const
{
    return totalCost;
}

bool MicrogridManager::isSimulationRunning() const
{
    return simulationRunning;
}

void MicrogridManager::initializeComponents()
{
    for (Component* component : componentsMap) {
        // 初始化每个组件
        component->setPower(0);
    }
}

void MicrogridManager::calculateTotalPower()
{
    totalPower = 0.0;
    for (Component* component : componentsMap) {
        totalPower += component->getPower();
    }
    emit powerUpdated(totalPower);
}

void MicrogridManager::calculateTotalCost()
{
    totalCost = 0.0;
    for (Component* component : componentsMap) {
        // 假设每个组件都有一个calculateCost方法
        // 实际实现中可能需要动态转换组件类型
        if (DieselGenerator* diesel = dynamic_cast<DieselGenerator*>(component)) {
            totalCost += diesel->calculateCost();
        }
        // 处理其他类型组件的成本计算
    }
    emit costUpdated(totalCost);
}

bool MicrogridManager::validateComponent(Component* component) const
{
    // 验证组件是否有效
    if (!component) return false;
    if (component->getName().isEmpty()) return false;
    return true;
}

// 槽函数实现
void MicrogridManager::onPriceDataChanged(const QVector<double>& newPrices)
{
    electricityPrices = newPrices;
    emit statusUpdated("电价数据已更新");
}

void MicrogridManager::onLoadProfileChanged(const QVector<double>& newProfile)
{
    loadProfile = newProfile;
    emit statusUpdated("负荷曲线已更新");
}

void MicrogridManager::onComponentParameterChanged(const QString& componentName)
{
    Component* component = getComponent(componentName);
    if (component) {
        emit componentUpdated(componentName);
        emit statusUpdated(QString("组件参数已更新: %1").arg(componentName));

        // 重新计算总功率和成本
        calculateTotalPower();
        calculateTotalCost();
    }
}
